using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Data.SqlClient;
using System.Data;

namespace SpiderService
{
	public class ReadFetchQueuesThread : ThreadBase
	{
		private static AutoResetEvent s_Signal;

		static ReadFetchQueuesThread()
		{
			s_Signal = new AutoResetEvent(true);
		}

		public static void Set()
		{
			s_Signal.Set();
		}

		protected override void DoWork()
		{
			com.spider.SpiderService spider = new com.spider.SpiderService();
			while (this.started)
			{
				s_Signal.WaitOne(TimeSpan.FromSeconds(Globals.ReadFetchQueuesSleepTime));
				if (this.started)
				{
					try
					{
						DataTable dt = spider.GetSpiderFetchQueues();
						foreach (DataRow dr in dt.Rows)
						{
							int projectId = Convert.ToInt32(dr["ProjectId"]);
							string url = Convert.ToString(dr["Url"]);

							if (!string.IsNullOrEmpty(url))
							{
								WebFileInfo wfi = new WebFileInfo();
								wfi.ProjectId = projectId;
								wfi.Url = (url.StartsWith("http://") ? url : "http://" + url);
								Globals.LinkItemMQ.Send(wfi);
							}
						}
					}
					catch (Exception ex)
					{
						Globals.FileLog.WriteError(ex);
					}
				}
			}
		}

		protected override void OnStop()
		{
			Set();
		}
	}
}
